package com.yjd.back.system.control;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.mail.model.MailModel;
import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.service.ISysParamService;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.util.MailUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.vo.Constant.SysParamKeyEnum;

@Controller
@Scope("prototype")
@RequestMapping("/SetupEmail/")
public class MailSetupControl extends BaseControl{
	
	@Resource
	ISysParamService sysParamService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("config")
	public String setupEmail(HttpServletRequest request) throws Exception{
		SysParamModel pmodel=SysParamUtil.getSysParamModel(SysParamKeyEnum.MAIL_CONFIG);
		Map<String,String> config=(Map<String, String>) JSON.parse(pmodel.getParam_value());
		config.put("auth", config.get("mail.smtp.auth"));
		request.setAttribute("config", config);
		return "email.setup";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("update")
	public void update(HttpServletRequest request)
			throws Exception {
		Map<String,Object> map=ServletUtil.getParameterMap(request);
		SysParamModel pmodel=SysParamUtil.getSysParamModel(SysParamKeyEnum.MAIL_CONFIG);
		Map<String,String> config=(Map<String, String>) JSON.parse(pmodel.getParam_value());
		for (Map.Entry<String, String> entry : config.entrySet()) {
			if(map.get(entry.getKey())!=null){
				if(!((String)map.get(entry.getKey())).equals(entry.getValue())){
					config.put(entry.getKey(), (String) map.get(entry.getKey()));				}
			}
		}
		if(map.get("auth")!=null){
			config.put("mail.smtp.auth", (String)map.get("auth"));
		}
		
		pmodel.setParam_value(JSON.toJSONString(config));
		Integer i=sysParamService.update(pmodel, this.getOperParamDto());
		if (i > 0) {
			MailUtil.getUtil().setConfig(config);
			this.successMsg(null, "更新成功！");
		} else {
			this.errorMsg(null, "更新失败！请联系管理员");
		}
	}
	@RequestMapping("sendMail")
	public String sendMail(){
		return "email.send";
	}
	
	@RequestMapping("send")
	public void send(HttpServletRequest requst) throws Exception{
		Map<String,Object> map=ServletUtil.getParameterMap(request);
		MailUtil util=MailUtil.getUtil();
		try{
		util.sendMail(getMailContent(map));
		}catch(Exception e){
			e.printStackTrace();
			this.errorMsg(null, "邮件发送失败！");
			return;
		}
		this.successMsg(null, "邮件发送成功！");
	}
	
	
	public MailModel getMailContent(Map<String,Object> map) {
		MailModel mm = new MailModel();
		mm.setToEmail((String) map.get("mailto"));
		mm.setMailContent((String) map.get("content"));
		mm.setSubject((String) map.get("title"));
		return mm;
	}
}
